<?php session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--
//  Copyright (C) 2004-2006  Autodesk, Inc.
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of version 2.1 of the GNU Lesser
//  General Public License as published by the Free Software Foundation.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-->
<html>

<head>
<?php include("config.php");
      include("utils.php");
	  include(ROOT_DIR_CLASES.'/cCliente.php');
?>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta http-equiv="content-script-type" content="text/javascript">
    <meta http-equiv="content-style-type" content="text/css">
    <link href="<?php echo ESTILO?>/globalStyles.css" rel="stylesheet" type="text/css">
	<link href="<?php echo ESTILO?>/otherStyles.css" rel="stylesheet" type="text/css">
	<link href="<?php echo ESTILO?>/viewer.css" rel="stylesheet" type="text/css">
	<link href="<?php echo ESTILO?>/bykom.css" rel="stylesheet" type="text/css">

    
</head>

<body onLoad="OnPageLoad()"> 

	
<?php
ini_set("display_errors","1");
    error_reporting(E_ALL);
require_once('../common.php');
require_once($webExtensionsDirectory . 'www/mapviewerphp/layerdefinitionfactory.php');	
require_once('layer_functions.php');
try
{
	//---------------------------------------------------//
		$cuenta=$_SESSION['v'];
		
	//---------------------------------------------------//   	    
   	// Initialize
    MgInitializeWebTier($webconfigFilePath);
    $sessionId = ($_SERVER['REQUEST_METHOD'] == "POST")?$_POST['SESSION']: $_GET['SESSION'];
    $userInfo = new MgUserInformation($sessionId);
    $siteConnection = new MgSiteConnection();
    $siteConnection->Open($userInfo);
    $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
    $featureService = $siteConnection->CreateService(MgServiceType::FeatureService);      
           
    //---------------------------------------------------//
    // Open the map
    $map = new MgMap();
    $map->Open($resourceService, AVL_MAP);
    
    $cuenta=$_SESSION['v'];
    $cuentas=BykomCliente::Cuentas_Cliente_Movil($cuenta);

    if ($cuentas->cantidad() > 1) // tiene mas moviles que el actual en la flota
    {
       		for($i=0;$i<$cuentas->cantidad();$i++)
	   		{
		     	
	   			if ($cuentas->campo('ORDER_ID',$i) <> $cuenta)
	   			{
	   			$cuentaActual = $cuentas->campo('ORDER_ID',$i);
	   			$datosIdentificacion = BykomCliente::Consulta_Datos_Identificacion_Avl($cuentaActual);
                $movil = $datosIdentificacion->campo('Movil',0);
   				$descripcion = $datosIdentificacion->campo('Descripcion',0);
   				$identificador =$datosIdentificacion->campo('Identificador',0);
   				$marca = $datosIdentificacion->campo('Marca',0);
   				$modelo = $datosIdentificacion->campo('Modelo',0);
   				$patente = $datosIdentificacion->campo('Patente',0);
                $datosPosicionamiento = BykomCliente::Consulta_PosicionActual_Avl($cuentaActual);
        		$registro = $datosPosicionamiento->cantidad();
        		
        		if ($registro > 0)
        		{
        			$registro = $datosPosicionamiento->cantidad()-1;
   	    			$longitud = quitCero($datosPosicionamiento->campo('longitud',0));
        			$latitud = quitCero($datosPosicionamiento->campo('latitud',0));
        			$velocidad = $datosPosicionamiento->campo('velocidad',0);
        			$sentido = $datosPosicionamiento->campo('sentido',0);
        			$sentidoPalabra = BykomCliente::Obtener_Palabra_Sentido($sentido);
        			$satelites = $datosPosicionamiento->campo('satelites',0);
        			$direccion = $datosPosicionamiento->campo('direccion',0);
        			$direccionAbrev = BykomCliente::Obtener_Direccion_Abreviada($direccion);
        			$evento = $datosPosicionamiento->campo('evento',0);
        			$validez = BykomCliente::Obtener_Palabra_Validez($datosPosicionamiento->campo('validez',0));
        			$fechaMensaje = $datosPosicionamiento->campo('fechaMensaje',0);
        			$statusZona = $datosPosicionamiento->campo('statusZona',0);
          			if ($statusZona == 390)
        			{
        				$zonaProhibida = $datosPosicionamiento->campo('zonaProhibida',0);
        			}
    //---------------------------------------------------//
	// Create a feature class definition for the new feature source
	$name = "Points".$cuentaActual;
	$classDefinition = getPointClassDefinition($name);
	$featureSchema = new MgFeatureSchema("PointSchema", "Point schema");
	$featureSchema->GetClasses()->Add($classDefinition);             
	
	$featureSourceName = "Session:$sessionId//".$name.".FeatureSource";
	$resourceIdentifier = new MgResourceIdentifier($featureSourceName);
	$wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
	$sdfParams = new MgCreateSdfParams("ArbitraryXY", $wkt, $featureSchema);
    $featureService->CreateFeatureSource($resourceIdentifier, $sdfParams);
	
	$batchPropertyCollection = new MgBatchPropertyCollection();
	$wktReaderWriter = new MgWktReaderWriter();
	$agfReaderWriter = new MgAgfReaderWriter();
	$geometryFactory = new MgGeometryFactory();

	$propertyCollection = MakePoint("Point A", $longitud, $latitud);
	$batchPropertyCollection->Add($propertyCollection);
	unset($propertyCollection);	
		
	$cmd = new MgInsertFeatures($name, $batchPropertyCollection); 
	$featureCommandCollection = new MgFeatureCommandCollection();
	$featureCommandCollection->Add($cmd);
	
	$featureService->UpdateFeatures($resourceIdentifier, $featureCommandCollection, false);    
	
    //---------------------------------------------------//
    // Create a new layer
    
    $factory = new LayerDefinitionFactory();
    $resourceId = AVL_SYMBOLS;
    $symbolName = 'PushPin - Blue';
    $width = '24';  // unit = points
    $height = '24'; // unit = points
    $color = 'FFFF0000';
    $markSymbol = $factory->CreateMarkSymbol($resourceId, $symbolName, $width, $height, $color);   
    
    // Create a text symbol
    $text = "ID";
    $fontHeight="12";
    $foregroundColor = 'FF000000';
    $textSymbol = $factory->CreateTextSymbol($text, $fontHeight, $foregroundColor);

    // Create a point rule.
    $legendLabel = 'trees';
    $filter = '';
    $pointRule = $factory->CreatePointRule($legendLabel, $filter, $textSymbol, $markSymbol);
      
    // Create a point type style.
    $pointTypeStyle = $factory->CreatepointTypeStyle($pointRule);
      
    // Create a scale range.
    $minScale = '0';
    $maxScale = '1000000000000';
    $pointScaleRange = $factory->CreateScaleRange($minScale, $maxScale, $pointTypeStyle);      

    // Create the layer definiton.
    $featureName = 'PointSchema:'.$name;
    $geometry = 'GEOM';
    
    $layerDefinition = $factory->CreateLayerDefinition($featureSourceName, $featureName, $geometry, $pointScaleRange);
    
    //---------------------------------------------------//
    // Add the layer to the map
    $newLayer = add_layer_definition_to_map($layerDefinition, $name, $descripcion, $sessionId, $resourceService, $map);
    add_layer_to_group($newLayer, "Flota", "Flota", $map);

    $layerCollection = $map->GetLayers();
    if ($layerCollection->Contains($name))
    {
        $pointsLayer =$layerCollection->GetItem("Points".$cuentaActual);
        $pointsLayer->SetVisible(true);
    }
    
    //---------------------------------------------------//
    //  Save the map back to the session repository
    $sessionIdName = "Session:$sessionId//".AVL_MAP.".Map";
    $sessionResourceID = new MgResourceIdentifier($sessionIdName);
	$sessionResourceID->Validate();
    $map->Save($resourceService, $sessionResourceID);
        		}
	   			}
	   		}
    }

    //---------------------------------------------------//
}
catch (MgException $e)
{
	echo "<script language=\"javascript\" type=\"text/javascript\"> \n";
	echo "    alert(\" " . $e->GetMessage() . " \"); \n";
	echo "</script> \n";
}

///////////////////////////////////////////////////////////////////////////////////
?>
<script language="javascript" type="text/javascript">
        function OnPageLoad()
        {
        	parent.mapFrame.Refresh();
            //parent.mapFrame.ZoomToScale(0.5);
            parent.mapFrame.ZoomToView(<?= $longitud ?>, <?= $latitud ?>, <?= ZOOM_AVL ?>, true);
        }
    </script>
</body>
</html>


